package com.example.controller;

import com.example.common.Result;
import com.example.entity.Product;
import com.example.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
    private final ProductService productService;
    
    @Value("${server.port}")
    private String serverPort;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }
    @PostMapping("/create")
    public Result<Product> create(@RequestBody Product product) {
        Product result = productService.create(product);
        log.info("创建商品：" + result);
        return Result.success(result);
    }

    @GetMapping("/get/{id}")
    public Result<Product> getProductById(@PathVariable("id") Long id) {
        Product product = productService.getProductById(id);
        if (product != null) {
            return Result.success(product);
        } else {
            return Result.error("商品不存在");
        }
    }

    @GetMapping("/list")
    public Result<List<Product>> getAllProducts() {
        return Result.success(productService.getAllProducts());
    }

    @PutMapping("/stock/{id}/{quantity}")
    public Result<Boolean> updateStock(@PathVariable("id") Long id, @PathVariable("quantity") int quantity) {
        boolean success = productService.updateStock(id, quantity);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("库存不足");
        }
    }

    @GetMapping("/port")
    public String getPort() {
        return serverPort;
    }
} 